import React, { Component } from 'react'
import { Switch, Route, Redirect } from 'react-router-dom'
import {connect} from 'react-redux'
import FrameLayout from './layout'
import { getMenuAsync } from './actions/user'

@connect(state => ({
  token: state.user.token,
  menus: state.user.menus
}), {
  getMenu: getMenuAsync
})
class App extends Component {

  _renderRoute = routes => {
    return routes.map(route => {
      if (!route) {
        return null
      }
      let el
      if (route.children) {
        el = this._renderRoute(route.children)
      } else {
        el = <Route key={route.path} path={route.path} component={route.component} />
      }

      if (route.redirect) {
        el = [el, (
          <Redirect key={route.path} from={route.path} to={route.redirect} exact />
        )]
      }

      return el
    })
  }

  async componentDidMount() {
    if (this.props.menus.length === 0) {
      this.props.getMenu()
    }
  }

  render() {
    return (
      this.props.token
      ?
      (
        this.props.menus.length
        ?
        <FrameLayout>
          <Switch>
            {
              this._renderRoute(this.props.menus).flat(Infinity)
            }
            <Redirect from="/admin" to="/admin/dashboard" exact />
            <Redirect to="/404" />
          </Switch>
        </FrameLayout>
        :
        <FrameLayout />
      )
      :
      <Redirect to="/login" />
    )
  }
}

export default App